<template>
  <div class="inpatient-slip-container">
    <!-- 功能描述区域 -->
    <div class="description-section">
      <h2>三、住院单设置</h2>
      <div class="description-content">
        <div class="desc-item">
          <strong>功能描述：</strong>
          <p>配置住院患者入院、出院、转科等环节的单据模板，涵盖床位费计算规则、护理级别、押金预警阈值等核心参数，确保住院流程标准化。</p>
        </div>
        <div class="desc-item">
          <strong>操作流程：</strong>
          <p>管理员进入“住院单设置”，选择病区或科室，设置床位费日结标准、护理等级与费用映射关系；配置押金不足时的预警方式（如短信通知家属），保存后系统自动校验住院费用计算逻辑。</p>
        </div>
      </div>
    </div>

    <!-- 住院单设计界面 -->
    <el-card class="design-card">
      <template #header>
        <div class="card-header">
          <span>住院单设计</span>
          <el-button text @click="handleClose">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>

      <div class="design-wrapper">
        <!-- 标题文本输入 -->
        <div class="title-input-section">
          <el-input
            v-model="titleText"
            placeholder="请输入标题文本"
            class="title-input"
          >
            <template #prepend>标题文本</template>
          </el-input>
        </div>

        <!-- 主要内容区域 -->
        <div class="main-content">
          <!-- 左侧：设计区和打印项目 -->
          <div class="left-section">
            <div class="design-area-wrapper">
              <div class="area-label">设计区</div>
              <div class="design-area" ref="designAreaRef">
                <div
                  v-for="(item, index) in selectedItems"
                  :key="index"
                  class="design-item"
                  @click="removeDesignItem(index)"
                >
                  <span>{{ item.label }}</span>
                  <el-icon class="remove-icon"><Close /></el-icon>
                </div>
                <div v-if="selectedItems.length === 0" class="empty-hint">
                  点击右侧复选框或"添加项目"按钮添加打印项目
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧：预览区和打印项目列表 -->
          <div class="right-section">
            <!-- 预览区 -->
            <div class="preview-area-wrapper">
              <div class="area-label">预览区</div>
              <div class="preview-area">
                <div class="preview-content">
                  <div class="preview-title">{{ titleText || '住院单' }}</div>
                  <div
                    v-for="(item, index) in selectedItems"
                    :key="index"
                    class="preview-item"
                  >
                    <span class="preview-label">{{ item.label }}：</span>
                    <span class="preview-value">{{ getPreviewValue(item.key) }}</span>
                  </div>
                  <div v-if="selectedItems.length === 0" class="preview-empty">
                    暂无预览内容
                  </div>
                </div>
              </div>
            </div>

            <!-- 打印项目列表 -->
            <div class="print-items-section">
              <div class="section-header">
                <span>打印项目</span>
                <div class="header-actions">
                  <el-button size="small" @click="handleAddItem">
                    <el-icon><Plus /></el-icon>
                    添加项目
                  </el-button>
                  <el-button size="small" @click="handlePrint">
                    <el-icon><Printer /></el-icon>
                    打印
                  </el-button>
                </div>
              </div>
              <div class="print-items-list">
                <el-checkbox-group v-model="selectedKeys" @change="handleSelectionChange">
                  <el-checkbox
                    v-for="item in printItems"
                    :key="item.key"
                    :label="item.key"
                    class="print-item-checkbox"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部操作按钮 -->
        <div class="action-buttons">
          <el-button type="primary" @click="handleSave">
            <el-icon><DocumentChecked /></el-icon>
            保存
          </el-button>
          <el-button @click="handleClear">
            <el-icon><Delete /></el-icon>
            清空
          </el-button>
          <el-button @click="handlePreview">
            <el-icon><View /></el-icon>
            预览
          </el-button>
          <el-button type="danger" @click="handleDelete">
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </div>

        <!-- AI识图下拉菜单 -->
        <div class="ai-section">
          <el-dropdown @command="handleAiCommand">
            <span class="ai-dropdown">
              AI识图
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="recognize">识别图片内容</el-dropdown-item>
                <el-dropdown-item command="generate">生成模板</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { writeApi } from '@/api/http'

// 打印项目列表（住院场景，可按需再调整）
const printItems = ref([
  { key: 'number', label: '编号' },
  { key: 'ward', label: '病区' },
  { key: 'department', label: '科室' },
  { key: 'doctor', label: '主管医生' },
  { key: 'nursingLevel', label: '护理级别' },
  { key: 'bedNumber', label: '病床号' },
  { key: 'admissionTime', label: '入院时间' },
  { key: 'transferDepartment', label: '转科' },
  { key: 'dischargeTime', label: '出院时间' },
  { key: 'deposit', label: '押金' },
  { key: 'consumptionDetails', label: '费用明细' },
  { key: 'cashier', label: '收费员' },
  { key: 'amount', label: '合计金额' },
])

// 标题文本
const titleText = ref('住院单')

// 选中的项目key列表
const selectedKeys = ref<string[]>([])

// 选中的项目对象列表（用于显示在设计区）
const selectedItems = computed(() => {
  return printItems.value.filter(item => selectedKeys.value.includes(item.key))
})

// 设计区引用
const designAreaRef = ref<HTMLElement | null>(null)

// 预览值映射
const getPreviewValue = (key: string) => {
  const previewValues: Record<string, string> = {
    number: 'ZY-0001',
    ward: '一病区',
    department: '内科',
    doctor: '王主任',
    nursingLevel: '二级护理',
    bedNumber: 'A301',
    admissionTime: '2024-01-10 09:00',
    transferDepartment: '-',
    dischargeTime: '-',
    deposit: '¥3000',
    consumptionDetails: '床位费、护理费、药费',
    cashier: '李收费员',
    amount: '¥5680.00',
  }
  return previewValues[key] || '-'
}

// 处理选择变化
const handleSelectionChange = () => {}

// 添加项目
const handleAddItem = () => {
  if (selectedKeys.value.length === printItems.value.length) {
    ElMessage.warning('所有项目已添加')
    return
  }
  const firstUnselected = printItems.value.find(
    item => !selectedKeys.value.includes(item.key)
  )
  if (firstUnselected) {
    selectedKeys.value.push(firstUnselected.key)
    ElMessage.success(`已添加：${firstUnselected.label}`)
  }
}

// 从设计区移除项目
const removeDesignItem = (index: number) => {
  const item = selectedItems.value[index]
  if (!item) return
  selectedKeys.value = selectedKeys.value.filter(key => key !== item.key)
  ElMessage.success(`已移除：${item.label}`)
}

// 当前模板ID（存在则执行更新，不存在则创建）
const currentTemplateId = ref<number | null>(null)
// 删除人（删除接口所需）
const deletedBy = ref<string>('admin')

// 保存（存在 TemplateId 调用更新；否则创建）
const handleSave = async () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请至少选择一个打印项目')
    return
  }
  try {
    const payloadBase = {
      TemplateName: titleText.value || '住院单',
      Description: '住院单模板',
      IsActive: true,
      IsDefault: false,
      PriorityRules: '{}',
      ConfiguredFields: JSON.stringify(selectedKeys.value),
    }
    if (currentTemplateId.value == null) {
      await writeApi.post('/Management/Create', payloadBase)
      ElMessage.success('创建成功')
    } else {
      const updatePayload = {
        TemplateId: currentTemplateId.value,
        ...payloadBase,
      }
      await writeApi.put('/Management/Update', updatePayload)
      ElMessage.success('更新成功')
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 清空
const handleClear = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有内容吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    selectedKeys.value = []
    titleText.value = '住院单'
    ElMessage.success('已清空')
  } catch {}
}

// 预览
const handlePreview = () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请至少选择一个打印项目')
    return
  }
  ElMessage.info('预览功能：可以在预览区查看效果')
}

// 打印
const handlePrint = () => {
  if (selectedKeys.value.length === 0) {
    ElMessage.warning('请至少选择一个打印项目')
    return
  }
  ElMessage.info('打印功能：可以调用浏览器打印功能')
}

// 关闭
const handleClose = () => {
  ElMessage.info('关闭功能：可以返回上一页')
}

// AI识图命令处理
const handleAiCommand = (command: string) => {
  if (command === 'recognize') {
    ElMessage.info('AI识别图片功能')
  } else if (command === 'generate') {
    ElMessage.info('AI生成模板功能')
  }
}

// 删除
const handleDelete = async () => {
  if (currentTemplateId.value == null) {
    ElMessage.warning('暂无可删除的模板（缺少 TemplateId）')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await writeApi.delete('/Management/Delete', {
      params: { templateId: currentTemplateId.value, deletedBy: deletedBy.value },
    })
    ElMessage.success('删除成功')
    currentTemplateId.value = null
    selectedKeys.value = []
    titleText.value = '住院单'
  } catch {}
}
</script>

<style scoped lang="scss">
.inpatient-slip-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.description-section {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  h2 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 18px;
  }

  .description-content {
    .desc-item {
      margin-bottom: 15px;

      strong {
        color: #409eff;
      }

      p {
        margin: 5px 0 0 0;
        color: #666;
        line-height: 1.6;
      }
    }
  }
}

.design-card {
  :deep(.el-card__header) {
    padding: 15px 20px;
    background-color: #fafafa;
  }

  :deep(.el-card__body) {
    padding: 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 16px;
}

.design-wrapper {
  .title-input-section {
    margin-bottom: 20px;

    .title-input {
      max-width: 400px;
    }
  }

  .main-content {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;

    .left-section {
      flex: 1;

      .design-area-wrapper {
        .area-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .design-area {
          min-height: 500px;
          border: 2px dashed #dcdfe6;
          border-radius: 4px;
          padding: 20px;
          background-color: #fff;
          position: relative;

          .design-item {
            display: inline-block;
            padding: 8px 15px;
            margin: 5px;
            background-color: #ecf5ff;
            border: 1px solid #b3d8ff;
            border-radius: 4px;
            cursor: pointer;
            position: relative;
            transition: all 0.3s;

            &:hover {
              background-color: #d9ecff;
              border-color: #409eff;

              .remove-icon {
                display: inline-block;
              }
            }

            .remove-icon {
              display: none;
              margin-left: 8px;
              color: #f56c6c;
              font-size: 14px;
            }
          }

          .empty-hint {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #999;
            font-size: 14px;
          }
        }
      }
    }

    .right-section {
      width: 400px;
      display: flex;
      flex-direction: column;
      gap: 20px;

      .preview-area-wrapper {
        .area-label {
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;
          font-weight: 500;
        }

        .preview-area {
          min-height: 300px;
          border: 2px dashed #dcdfe6;
          border-radius: 4px;
          padding: 20px;
          background-color: #fff;

          .preview-content {
            .preview-title {
              font-size: 18px;
              font-weight: bold;
              text-align: center;
              margin-bottom: 20px;
              padding-bottom: 10px;
              border-bottom: 2px solid #e4e7ed;
            }

            .preview-item {
              margin-bottom: 12px;
              font-size: 14px;

              .preview-label {
                color: #666;
                margin-right: 8px;
              }

              .preview-value {
                color: #333;
                font-weight: 500;
              }
            }

            .preview-empty {
              text-align: center;
              color: #999;
              margin-top: 50px;
            }
          }
        }
      }

      .print-items-section {
        flex: 1;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        padding: 15px;
        background-color: #fafafa;

        .section-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 15px;
          font-weight: 500;
          font-size: 14px;

          .header-actions {
            display: flex;
            gap: 8px;
          }
        }

        .print-items-list {
          max-height: 400px;
          overflow-y: auto;

          .print-item-checkbox {
            display: block;
            margin-bottom: 10px;
            padding: 5px 0;

            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
    }
  }

  .action-buttons {
    display: flex;
    gap: 10px;
    justify-content: center;
    margin-bottom: 20px;
  }

  .ai-section {
    text-align: center;

    .ai-dropdown {
      cursor: pointer;
      color: #409eff;
      font-size: 14px;

      &:hover {
        color: #66b1ff;
      }
    }
  }
}
</style>


